<pre class='metadata'>
Title: Intersection Observer
Status: ED
ED: https://w3c.github.io/IntersectionObserver/
Shortname: intersection-observer
TR: https://www.w3.org/TR/intersection-observer/
Previous version: from biblio
Level: none
Editor: Stefan Zager, Google, szager@google.com, w3cid 91208
Editor: Emilio Cobos Álvarez , Mozilla, emilio@mozilla.com, w3cid 106537
Editor: Traian Captan, Google, tcaptan@google.com, w3cid 137959
Former Editor: Michael Blain, Google, mpb@google.com, w3cid 73819
Abstract: This specification describes an API that can be used to understand the visibility and position of DOM elements ("targets") relative to a containing element or to the top-level viewport ("root"). The position is delivered asynchronously and is useful for understanding the visibility of elements and implementing pre-loading and deferred loading of DOM content.
Group: webapps
Repository: W3C/IntersectionObserver
Test Suite: http://w3c-test.org/intersection-observer/
Ignored Vars: rootMargin, docs, now
Markup Shorthands: markdown yes
</pre>

<pre class="anchors">
urlPrefix: https://dom.spec.whatwg.org/
	url: #node-trees; type: dfn; text: node tree
urlPrefix: http://www.w3.org/TR/hr-time/
	type: typedef; text: DOMHighResTimeStamp
	type: dfn; text: time origin
urlPrefix: https://html.spec.whatwg.org/multipage/
	urlPrefix: dom.html
		url: #document; type:dfn; text: Document
	urlPrefix: browsers.html
		type: dfn; text: browsing context
		type: dfn; text: top-level browsing context
		type: dfn; text: nested browsing context
		type: dfn; text: list of the descendant browsing contexts
		type: dfn; text: browsing context container
		type: dfn; text: fully active
	urlPrefix: webappapis.html;
		type: dfn; text: report the exception
		type: dfn; text: event loop
		type: dfn; text: queue a task
		type: dfn; text: run the fullscreen rendering steps
		type: dfn; text: run the animation frame callbacks
		url: #event-loop-processing-model; type: dfn; text: HTML Event Loops Processing Model
		type: dfn; text: relevant settings object
		url: #concept-environment-top-level-origin; type: dfn; text: top-level origin
	urlPrefix: infrastructure.html;
		url: #dfn-callback-this-value; type: dfn; text: callback this value
	urlPrefix: origin.html
		type: dfn; text: origin
urlPrefix: https://heycam.github.io/webidl/
	url: #dfn-simple-exception; type:exception;
		text: RangeError
		text: TypeError
		text: SyntaxError
	urlPrefix: #dfn-; type:dfn; text: throw
	urlPrefix: #idl-; type:interface; text: double
	urlPrefix: #idl-; type:interface; text: undefined
	url: #hierarchyrequesterror; type: exception; text: HierarchyRequestError
urlPrefix: https://drafts.csswg.org/css-box/
	url: #containing-block; type: dfn; text: containing block
	url: #padding-area; type: dfn; text: padding area
	url: #padding-edge; type: dfn; text: padding edge
urlPrefix: https://drafts.csswg.org/css-display/
	url: #containing-block-chain; type: dfn; text: containing block chain
urlPrefix: http://www.w3.org/TR/css-masking-1/
	url: #propdef-clip-path; type:dfn; text: clip-path
urlPrefix: https://drafts.csswg.org/cssom-view-1/
	url: #pinch-zoom; type:dfn; text: pinch zoom
urlPrefix: https://drafts.csswg.org/css2/visuren.html
	url: #viewport; type:dfn; text: viewport
urlPrefix: https://drafts.csswg.org/css-overflow-3/
	url: #overflow-properties; type:dfn; text: overflow properties
</pre>

<pre class="link-defaults">
spec: css-values-3; type: dfn
	text: absolute length
	text: dimension
spec:html; type:attribute; text:document
</pre>

<h2 id='introduction'>Introduction</h2>

The web's traditional position calculation mechanisms
rely on explicit queries of DOM state
that are known to cause (expensive) style recalculation and layout
and, frequently, are a source of significant performance overhead
due to continuous polling for this information.

A body of common practice has evolved that relies on these behaviors,
however, including (but not limited to):

* Building custom pre- and deferred-loading of DOM and data.
* Implementing data-bound high-performance scrolling lists
	which load and render subsets of data sets.
	These lists are a central mobile interaction idiom.
* Calculating element visibility.
	In particular,
	<a href="http://www.iab.net/iablog/2014/03/viewability-has-arrived-what-you-need-to-know-to-see-through-this-sea-change.html">
	ad networks now require reporting of ad "visibility" for monetizing impressions</a>. This has led to many sites abusing scroll handlers
	(causing jank on scroll),
	<a href="http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html">
	synchronous layout invoking readbacks</a>
	(causing unnecessary critical work in rAF loops),
	and resorting to exotic plugin-based solutions for computing "true" element visibility (with all the associated overhead of the plugin architecture).

These use-cases have several common properties:

1. They can be represented as passive "queries"
	about the state of individual elements
	with respect to some other element
	(or the global <a>viewport</a>).
2. They do not impose hard latency requirements;
	that is to say, the information can be delivered asynchronously
	(e.g. from another thread)
	without penalty.
3. They are poorly supported by nearly all combinations of existing web platform features,
	requiring extraordinary developer effort despite their widespread use.

A notable non-goal is pixel-accurate information about what was actually displayed
(which can be quite difficult to obtain efficiently in certain browser architectures
in the face of filters, webgl, and other features).
In all of these scenarios the information is useful
even when delivered at a slight delay
and without perfect compositing-result data.

The Intersection Observer API addresses the above issues
by giving developers a new method to asynchronously query the position of an element
with respect to other elements or the global <a>viewport</a>.
The asynchronous delivery eliminates the need for costly DOM and style queries,
continuous polling,
and use of custom plugins.
By removing the need for these methods
it allows applications to significantly reduce their CPU, GPU and energy costs.

<div class="example">
	<pre highlight="js">
	var observer = new IntersectionObserver(changes => {
		for (const change of changes) {
			console.log(change.time);               // Timestamp when the change occurred
			console.log(change.rootBounds);         // Unclipped area of root
			console.log(change.boundingClientRect); // target.getBoundingClientRect()
			console.log(change.intersectionRect);   // boundingClientRect, clipped by its containing block ancestors, and intersected with rootBounds
			console.log(change.intersectionRatio);  // Ratio of intersectionRect area to boundingClientRect area
			console.log(change.target);             // the Element target
		}
	}, {});

	// Watch for intersection events on a specific target Element.
	observer.observe(target);

	// Stop watching for intersection events on a specific target Element.
	observer.unobserve(target);

	// Stop observing threshold events on all target elements.
	observer.disconnect();
	</pre>
</div>

<h2 id='intersection-observer-api'>Intersection Observer</h2>

The <dfn>Intersection Observer</dfn> API enables developers to understand the
visibility and position of <dfn for="IntersectionObserver">target</dfn> DOM
elements relative to an <a>intersection root</a>.

<h3 id='intersection-observer-callback'>
The IntersectionObserverCallback</h3>

<pre class="idl">
	callback IntersectionObserverCallback = undefined (sequence&lt;IntersectionObserverEntry> entries, IntersectionObserver observer);
</pre>

This callback will be invoked when there are changes to <a for="IntersectionObserver">target</a>'s
intersection with the <a>intersection root</a>, as per the
<a>processing model</a>.

<h3 id='intersection-observer-interface'>
The IntersectionObserver interface</h3>

The {{IntersectionObserver}} interface can be used to observe changes in the
intersection of an <a>intersection root</a> and one or more <a for="IntersectionObserver">target</a> {{Element}}s.

The <dfn for="IntersectionObserver">intersection root</dfn>
for an {{IntersectionObserver}} is the value of its {{IntersectionObserver/root}} attribute
if the attribute is non-<code>null</code>;
otherwise, it is the <a>top-level browsing context</a>'s {{document}} node,
referred to as the <dfn for="IntersectionObserver">implicit root</dfn>.

An {{IntersectionObserver}} with a non-<code>null</code> {{IntersectionObserver/root}}
is referred to as an <dfn for="IntersectionObserver">explicit root observer</dfn>,
and it can observe any <a for="IntersectionObserver">target</a> {{Element}} that is a descendant of the
{{IntersectionObserver/root}} in the <a>containing block chain</a>.
An {{IntersectionObserver}} with a <code>null</code> {{IntersectionObserver/root}}
is referred to as an <dfn for="IntersectionObserver">implicit root observer</dfn>.
Valid <a for="IntersectionObserver">targets</a> for an <a>implicit root observer</a> include
any {{Element}} in the <a>top-level browsing context</a>,
as well as any {{Element}} in any <a>nested browsing context</a>
which is in the <a>list of the descendant browsing contexts</a> of the <a>top-level browsing context</a>.

When dealing with <a>implicit root observers</a>, the API makes a distinction between
a <a for="IntersectionObserver">target</a> whose <a>relevant settings object</a>'s <a>origin</a> is
<a>same origin-domain</a> with the <a>top-level origin</a>, referred to as a
<dfn for="IntersectionObserver">same-origin-domain target</dfn>;
as opposed to a <dfn for="IntersectionObserver">cross-origin-domain target</dfn>.
Any <a for="IntersectionObserver">target</a> of an <a>explicit root observer</a> is also a <a>same-origin-domain target</a>,
since the <a for="IntersectionObserver">target</a> must be in the same <a>document</a> as the
<a>intersection root</a>.

Note: In {{MutationObserver}}, the {{MutationObserverInit}} options are passed
to {{MutationObserver/observe()}} while in {{IntersectionObserver}} they are
passed to the constructor. This is because for MutationObserver, each {{Node}}
being observed could have a different set of attributes to filter for. For
{{IntersectionObserver}}, developers may choose to use a single observer to
track multiple targets using the same set of options; or they may use a different
observer for each tracked target.
{{IntersectionObserverInit/rootMargin}} or {{threshold}} values for each
<a for="IntersectionObserver">target</a> seems to introduce more complexity without solving additional
use-cases. Per-{{observe()}} options could be provided in the future if the need arises.

<pre class="idl">
[Exposed=Window]
interface IntersectionObserver {
	constructor(IntersectionObserverCallback callback, optional IntersectionObserverInit options = {});
	readonly attribute (Element or Document)? root;
	readonly attribute DOMString rootMargin;
	readonly attribute DOMString scrollMargin;
	readonly attribute FrozenArray&lt;double&gt; thresholds;
	undefined observe(Element target);
	undefined unobserve(Element target);
	undefined disconnect();
	sequence&lt;IntersectionObserverEntry&gt; takeRecords();
};
</pre>

<div dfn-type="method" dfn-for="IntersectionObserver">
	: <dfn constructor lt="IntersectionObserver(callback, options = {})">
		new IntersectionObserver(callback, options)</dfn>
	::
		Return the result of running the <a>initialize a new IntersectionObserver</a>
		algorithm, providing |callback| and |options|.
	: <dfn>observe(target)</dfn>
	::
		Run the <a>observe a target Element</a> algorithm, providing |this| and |target|.
	: <dfn>unobserve(target)</dfn>
	::
		Run the <a>unobserve a target Element</a> algorithm, providing |this| and |target|.

		Note: {{MutationObserver}} does not implement {{unobserve()}}.
		For {{IntersectionObserver}}, {{unobserve()}} addresses the
		lazy-loading use case. After |target| becomes visible,
		it does not need to be tracked.
		It would be more work to either {{disconnect()}} all |target|s
		and {{observe()}} the remaining ones,
		or create a separate {{IntersectionObserver}} for each |target|.
	: <dfn>disconnect()</dfn>
	::
		For each |target| in |this|'s internal {{[[ObservationTargets]]}} slot:

		1. Remove the {{IntersectionObserverRegistration}} record
			whose {{IntersectionObserverRegistration/observer}} property is equal to |this|
			from |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot.
		2. Remove |target| from |this|'s internal {{[[ObservationTargets]]}} slot.
	: <dfn>takeRecords()</dfn>
	::
			1. Let |queue| be a copy of |this|'s internal {{[[QueuedEntries]]}} slot.
			2. Clear |this|'s internal {{[[QueuedEntries]]}} slot.
			3. Return |queue|.
</div>

<div dfn-type="attribute" dfn-for="IntersectionObserver">
	: <dfn>root</dfn>
	::
		The {{IntersectionObserverInit/root}} provided to the {{IntersectionObserver}} constructor, or <code>null</code> if none was provided.
	: <dfn>rootMargin</dfn>
	::
		Offsets applied to the <a>root intersection rectangle</a>,
		effectively growing or shrinking the box that is used to calculate intersections.
		<b>These offsets are only applied when handling <a>same-origin-domain targets</a>;
		for <a>cross-origin-domain targets</a> they are ignored.</b>

		On getting, return the result of serializing the elements of {{[[rootMargin]]}}
		space-separated, where pixel lengths serialize as the numeric value followed by "px",
		and percentages serialize as the numeric value followed by "%".  Note that
		this is not guaranteed to be identical to the |options|.{{IntersectionObserverInit/rootMargin}}
		passed to the {{IntersectionObserver}} constructor.  If no
		{{IntersectionObserverInit/rootMargin}} was passed to the {{IntersectionObserver}}
		constructor, the value of this attribute is "0px 0px 0px 0px".
	: <dfn>scrollMargin</dfn>
	::
		Offsets are applied to <a>scrollports</a> on the path from <a>intersection root</a> to <a for="IntersectionObserver">target</a>,
		effectively growing or shrinking the clip rects used to calculate intersections.

		On getting, return the result of serializing the elements of {{[[scrollMargin]]}}
		space-separated, where pixel lengths serialize as the numeric value followed by "px",
		and percentages serialize as the numeric value followed by "%".  Note that
		this is not guaranteed to be identical to the |options|.{{IntersectionObserverInit/scrollMargin}}
		passed to the {{IntersectionObserver}} constructor.  If no
		{{IntersectionObserverInit/scrollMargin}} was passed to the {{IntersectionObserver}}
		constructor, the value of this attribute is "0px 0px 0px 0px".
	: <dfn>thresholds</dfn>
	::
		A list of thresholds, sorted in increasing numeric order,
		where each threshold is a ratio of intersection area to bounding box area
		of an observed target.  Notifications for a target are generated when any
		of the thresholds are crossed for that target.
		If no |options|.{{IntersectionObserverInit/threshold}} was provided to the
		{{IntersectionObserver}} constructor, or the sequence is empty, the value
		of this attribute will be [0].
</div>

An {{Element}} is defined as having a <dfn for="IntersectionObserver">content clip</dfn> if its computed style has <a>overflow properties</a> that cause its content to be clipped to the element's <a>padding edge</a>.

The <dfn for=IntersectionObserver>root intersection rectangle</dfn>
for an {{IntersectionObserver}}
is the rectangle we'll use to check against the targets.

<dl class=switch>
	<dt>If the {{IntersectionObserver}} is an <a>implicit root observer</a>,
	<dd>it's treated as if the root were the <a>top-level browsing context</a>'s {{document}}, according to the following rule for {{document}}.

	<dt>If the <a>intersection root</a> is a {{document}},
	<dd>it's the size of the {{document}}'s <a>viewport</a> (note that this processing step can only be reached if the {{document}} is <a>fully active</a>).

	<dt>Otherwise, if the <a>intersection root</a> has a <a>content clip</a>,
	<dd>it's the element's <a>padding area</a>.

	<dt>Otherwise,
	<dd>it's the result of <a>getting the bounding box</a> for the <a>intersection root</a>.
</dl>

When calculating the <a>root intersection rectangle</a> for
a <a>same-origin-domain target</a>, the rectangle is then expanded
according to the offsets in the {{IntersectionObserver}}’s {{[[rootMargin]]}} slot
in a manner similar to CSS's 'margin' property,
with the four values indicating the amount the top, right, bottom, and left edges, respectively, are offset by,
with positive lengths indicating an outward offset.
Percentages are resolved relative to the width of the undilated rectangle.

Note: {{IntersectionObserver/rootMargin}} only applies to the <a>intersection root</a> itself.
If a <a for="IntersectionObserver">target</a> {{Element}} is clipped by an ancestor other than the
<a>intersection root</a>, that clipping is unaffected by
{{IntersectionObserver/rootMargin}}.

: To <dfn>apply scroll margin to a scrollport</dfn>
::
	When calculating a <a>scrollport</a> intersection rectangle for
	a <a>same-origin-domain target</a>, the rectangle is expanded
	according to the offsets in the {{IntersectionObserver}}’s {{[[scrollMargin]]}} slot
	in a manner similar to CSS's 'margin' property,
	with the four values indicating the amount the top, right, bottom, and left edges, respectively, are offset by,
	with positive lengths indicating an outward offset.
	Percentages are resolved relative to the width of the undilated rectangle.

	<b>These offsets are only applied when handling <a>same-origin-domain targets</a>;
	for <a>cross-origin-domain targets</a> they are ignored.</b>

	Note: {{IntersectionObserver/scrollMargin}} affects the clipping of <a for="IntersectionObserver">target</a>
	by all scrollable ancestors up to and including the <a>intersection root</a>.
	Both the {{IntersectionObserver/scrollMargin}} and the {{IntersectionObserver/rootMargin}}
	are applied to a scrollable <a>intersection root's</a> rectangle.

Note: <a>Root intersection rectangle</a> and <a>scrollport</a> intersection rectangles are not affected by
<a>pinch zoom</a> and will report the unadjusted <a>viewport</a>, consistent with the
intent of pinch zooming (to act like a magnifying glass and NOT change layout.)

To <dfn>parse a margin</dfn> (root or scroll)
from an input string |marginString|,
returning either a list of 4 pixel lengths or percentages,
or failure:

1. <a>Parse a list of component values</a> |marginString|,
	storing the result as |tokens|.
2. Remove all whitespace tokens from |tokens|.
3. If the length of |tokens| is greater than 4,
	return failure.
4. If there are zero elements in |tokens|,
	set |tokens| to ["0px"].
5. Replace each |token| in |tokens|:
	* If |token| is an <a>absolute length</a> <a>dimension</a> token,
		replace it with a an equivalent pixel length.
	* If |token| is a <<percentage>> token,
		replace it with an equivalent percentage.
	* Otherwise, return failure.
6. If there is one element in |tokens|,
	append three duplicates of that element to |tokens|.
	Otherwise, if there are two elements are |tokens|,
	append a duplicate of each element to |tokens|.
	Otherwise, if there are three elements in |tokens|,
	append a duplicate of the second element to |tokens|.
7. Return |tokens|.

<h3 id="intersection-observer-entry">
The IntersectionObserverEntry interface</h3>

<pre class="idl">
[Exposed=Window]
interface IntersectionObserverEntry {
	constructor(IntersectionObserverEntryInit intersectionObserverEntryInit);
	readonly attribute DOMHighResTimeStamp time;
	readonly attribute DOMRectReadOnly? rootBounds;
	readonly attribute DOMRectReadOnly boundingClientRect;
	readonly attribute DOMRectReadOnly intersectionRect;
	readonly attribute boolean isIntersecting;
	readonly attribute double intersectionRatio;
	readonly attribute Element target;
};

dictionary IntersectionObserverEntryInit {
	required DOMHighResTimeStamp time;
	required DOMRectInit? rootBounds;
	required DOMRectInit boundingClientRect;
	required DOMRectInit intersectionRect;
	required boolean isIntersecting;
	required double intersectionRatio;
	required Element target;
};
</pre>

<div dfn-type="attribute" dfn-for="IntersectionObserverEntry">
	: <dfn>boundingClientRect</dfn>
	::
		A {{DOMRectReadOnly}} obtained by <a>getting the bounding box</a>
		for {{IntersectionObserverEntry/target}}.
	: <dfn>intersectionRect</dfn>
	::
		{{IntersectionObserverEntry/boundingClientRect}}, intersected by
		each of {{IntersectionObserverEntry/target}}'s ancestors' clip
		rects (up to but not including {{IntersectionObserver/root}}),
		intersected with the <a>root intersection rectangle</a>.
		This value represents the portion of
		{{IntersectionObserverEntry/target}} actually visible
		within the <a>root intersection rectangle</a>.
	: <dfn>isIntersecting</dfn>
	::
		True if the {{IntersectionObserverEntry/target}} intersects with the
		{{IntersectionObserver/root}}; false otherwise.  This flag makes it
		possible to distinguish between an {{IntersectionObserverEntry}} signalling
		the transition from intersecting to not-intersecting; and an
		{{IntersectionObserverEntry}} signalling a transition from not-intersecting
		to intersecting with a zero-area intersection rect (as will happen with
		edge-adjacent intersections, or when the {{IntersectionObserverEntry/boundingClientRect}}
		has zero area).
	: <dfn>intersectionRatio</dfn>
	::
		If the {{IntersectionObserverEntry/boundingClientRect}} has non-zero area,
		this will be the ratio of {{IntersectionObserverEntry/intersectionRect}} area to
		{{IntersectionObserverEntry/boundingClientRect}} area.  Otherwise, this will be
		1 if the {{IntersectionObserverEntry/isIntersecting}} is true, and 0 if not.
	: <dfn>rootBounds</dfn>
	::
		For a <a>same-origin-domain target</a>, this will be the <a>root intersection rectangle</a>.
		Otherwise, this will be <code>null</code>.
		Note that if the target is in a different <a>browsing context</a> than the <a>intersection root</a>,
		this will be in a different coordinate system
		than {{IntersectionObserverEntry/boundingClientRect}} and {{IntersectionObserverEntry/intersectionRect}}.
	: <dfn>target</dfn>
	::
		The {{Element}} whose intersection with the
		<a>intersection root</a> changed.
	: <dfn>time</dfn>
	::
		The attribute must return a {{DOMHighResTimeStamp}}
		that corresponds to the time the intersection was recorded, relative to the
		<a>time origin</a> of the global object associated with the IntersectionObserver instance
		that generated the notification.
</div>

<h3 id="intersection-observer-init">
The IntersectionObserverInit dictionary</h3>

<pre class="idl">
dictionary IntersectionObserverInit {
	(Element or Document)?  root = null;
	DOMString rootMargin = "0px";
	DOMString scrollMargin = "0px";
	(double or sequence&lt;double>) threshold = 0;
};
</pre>

<div dfn-type="dict-member" dfn-for="IntersectionObserverInit">
	: <dfn>root</dfn>
	::
		The {{IntersectionObserver|root}} to use for intersection.
		If not provided, use the <a>implicit root</a>.
	: <dfn>rootMargin</dfn>
	::
		Similar to the CSS 'margin' property,
		this is a string of 1-4 components,
		each either an <a>absolute length</a> or a percentage.

		<pre class="example" highlight=js>
			"5px"                // all margins set to 5px
			"5px 10px"           // top & bottom = 5px, right & left = 10px
			"-10px 5px 8px"      // top = -10px, right & left = 5px, bottom = 8px
			"-10px -5px 5px 8px" // top = -10px, right = -5px, bottom = 5px, left = 8px
		</pre>
	: <dfn>scrollMargin</dfn>
	::
		Similar to {{IntersectionObserverInit/rootMargin}},
		this is a string of 1-4 components,
		each either an <a>absolute length</a> or a percentage.

		See {{IntersectionObserverInit/rootMargin}} above for the example.
	: <dfn>threshold</dfn>
	::
		List of threshold(s) at which to trigger callback.
		callback will be invoked when intersectionRect's area changes from
		greater than or equal to any threshold to less than that threshold,
		and vice versa.

		Threshold values must be in the range of [0, 1.0] and represent a
		percentage of the area of the rectangle produced
		by <a>getting the bounding box</a> for <a for="IntersectionObserver">target</a>.

		Note: 0.0 is effectively "any non-zero number of pixels".
</div>

<h2 dfn id='intersection-observer-processing-model'>
Processing Model</h2>

This section outlines the steps the user agent must take when implementing
the <a>Intersection Observer</a> API.

<h3 id='defines'>
Internal Slot Definitions</h3>

<h4 id='document-defines'>
Document</h4>

Each {{document}} has an
<dfn for="Document">IntersectionObserverTaskQueued</dfn> flag
which is initialized to false.

<h4 id='element-private-slots'>
Element</h4>

{{Element}} objects have an internal
<dfn attribute for=Element>\[[RegisteredIntersectionObservers]]</dfn> slot,
which is initialized to an empty list.
This list holds <dfn interface>IntersectionObserverRegistration</dfn> records,
which have an <dfn attribute for=IntersectionObserverRegistration>observer</dfn> property
holding an {{IntersectionObserver}}, a <dfn attribute for=IntersectionObserverRegistration>previousThresholdIndex</dfn> property
holding a number between -1 and the length of the observer's {{IntersectionObserver/thresholds}} property (inclusive), and
a <dfn attribute for=IntersectionObserverRegistration>previousIsIntersecting</dfn> property holding a boolean.

<h4 id='intersection-observer-private-slots'>
IntersectionObserver</h4>

{{IntersectionObserver}} objects have internal
<dfn attribute for=IntersectionObserver>\[[QueuedEntries]]</dfn> and
<dfn attribute for=IntersectionObserver>\[[ObservationTargets]]</dfn> slots,
which are initialized to empty lists and an internal
<dfn attribute for=IntersectionObserver>\[[callback]]</dfn> slot
which is initialized by {{IntersectionObserver(callback, options)}}</a>.
They also have internal <dfn attribute for=IntersectionObserver>\[[rootMargin]]</dfn>
and <dfn attribute for=IntersectionObserver>\[[scrollMargin]]</dfn> slots
which are lists of four pixel lengths or percentages.

<h3 id='algorithms'>
Algorithms</h2>

<h4 id='initialize-new-intersection-observer'>Initialize a new IntersectionObserver</h4>

To <dfn>initialize a new IntersectionObserver</dfn>, given an {{IntersectionObserverCallback}} |callback|
and an {{IntersectionObserverInit}} dictionary |options|, run these steps:

1. Let |this| be a new {{IntersectionObserver}} object
2. Set |this|'s internal {{[[callback]]}} slot to |callback|.
3. Attempt to <a>parse a margin</a>
	from |options|.{{IntersectionObserverInit/rootMargin}}.
	If a list is returned,
	set |this|'s internal {{[[rootMargin]]}} slot to that.
	Otherwise, <a>throw</a> a {{SyntaxError}} exception.
4. Attempt to <a>parse a margin</a>
	from |options|.{{IntersectionObserverInit/scrollMargin}}.
	If a list is returned,
	set |this|'s internal {{[[scrollMargin]]}} slot to that.
	Otherwise, <a>throw</a> a {{SyntaxError}} exception.
5. Let |thresholds| be a list equal to
	|options|.{{IntersectionObserverInit/threshold}}.
6. If any value in |thresholds| is less than 0.0 or greater than
	1.0, <a>throw</a> a {{RangeError}} exception.
7. Sort |thresholds| in ascending order.
8. If |thresholds| is empty, append <code>0</code> to |thresholds|.
9. The {{IntersectionObserver/thresholds}} attribute getter will return
	this sorted |thresholds| list.
10. Return |this|.

<h4 id='observe-target-element'>Observe a target Element</h4>

To <dfn>observe a target Element</dfn>, given an {{IntersectionObserver}} |observer|
and an {{Element}} |target|, follow these steps:

1. If |target| is in |observer|'s internal {{[[ObservationTargets]]}} slot,
	return.
2. Let |intersectionObserverRegistration| be
	an {{IntersectionObserverRegistration}} record
	with an {{IntersectionObserverRegistration/observer}} property set to |observer|,
	a {{IntersectionObserverRegistration/previousThresholdIndex}} property set to <code>-1</code>,
	and a {{IntersectionObserverRegistration/previousIsIntersecting}} property set to <code>false</code>.
3. Append |intersectionObserverRegistration|
	to |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot.
4. Add |target| to |observer|'s internal {{[[ObservationTargets]]}} slot.

<h4 id='unobserve-target-element'>Unobserve a target Element</h4>

To <dfn>unobserve a target Element</dfn>, given an {{IntersectionObserver}} |observer|
and an {{Element}} |target|, follow these steps:

1. Remove the {{IntersectionObserverRegistration}} record
	whose {{IntersectionObserverRegistration/observer}} property is equal to |this|
	from |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot, if present.
2. Remove |target| from |this|'s internal {{[[ObservationTargets]]}} slot, if present

<h4 id='queue-intersection-observer-task'>
Queue an Intersection Observer Task</h4>

The <dfn>IntersectionObserver task source</dfn> is a [=task source=] used for
scheduling tasks to [[#notify-intersection-observers-algo]].

To <dfn>queue an intersection observer task</dfn> for a {{document}} |document|,
run these steps:

1. If |document|'s <a>IntersectionObserverTaskQueued</a> flag is set to true,
	return.
2. Set |document|'s <a>IntersectionObserverTaskQueued</a> flag to true.
3. <a>Queue a task</a> on the <a>IntersectionObserver task source</a>
	associated with the {{document}}'s <a>event loop</a>
	to <a>notify intersection observers</a>.

<h4 id='notify-intersection-observers-algo'>
Notify Intersection Observers</h4>

To <dfn>notify intersection observers</dfn> for a {{document}} |document|,
run these steps:

1. Set |document|'s <a>IntersectionObserverTaskQueued</a> flag to false.
2. Let |notify list| be a list of all {{IntersectionObserver}}s
	whose {{IntersectionObserver/root}} is in the DOM tree of |document|.
3. For each {{IntersectionObserver}} object |observer| in |notify list|,
	run these steps:

	1. If |observer|'s internal {{[[QueuedEntries]]}} slot is empty,
		continue.
	2. Let |queue| be a copy of |observer|'s internal {{[[QueuedEntries]]}}
		slot.
	3. Clear |observer|'s internal {{[[QueuedEntries]]}} slot.
	4. Let |callback| be the value of |observer|'s internal {{[[callback]]}} slot.
	5. Invoke |callback| with |queue| as the first argument, |observer| as the second argument,
		and |observer| as the <a>callback this value</a>.
		If this throws an exception, <a>report the exception</a>.

<h4 id='queue-intersection-observer-entry-algo'>
Queue an IntersectionObserverEntry</h4>

To <dfn>queue an IntersectionObserverEntry</dfn> for an {{IntersectionObserver}} |observer|, given a
{{document}} |document|; {{DOMHighResTimeStamp}} |time|;
{{DOMRect}}s |rootBounds|, |boundingClientRect|, |intersectionRect|, and |isIntersecting| flag;
and an {{Element}} |target|;
run these steps:

1. Construct an {{IntersectionObserverEntry}}, passing in |time|, |rootBounds|,
	|boundingClientRect|, |intersectionRect|, |isIntersecting|, and |target|.
2. Append it to |observer|'s internal {{[[QueuedEntries]]}} slot.
3. <a>Queue an intersection observer task</a> for |document|.

<h4 id='calculate-intersection-rect-algo'>
Compute the Intersection of a Target Element and the Root</h4>

To <dfn>compute the intersection</dfn> between a <a for="IntersectionObserver">target</a> |target| and an <a>intersection root</a> |root|,
run these steps:

1. Let |intersectionRect| be the result of <a>getting the bounding box</a> for |target|.
2. Let |container| be the <a>containing block</a> of |target|.
3. While |container| is not |root|:
	1. If |container| is the {{document}} of a <a>nested browsing context</a>,
		update |intersectionRect| by clipping to the <a>viewport</a>
		of the {{document}}, and update |container| to be
		the <a>browsing context container</a> of |container|.
	2. Map |intersectionRect| to the coordinate space of |container|.
	3. If |container| is a <a>scroll container</a>, apply the {{IntersectionObserver}}’s
		{{[[scrollMargin]]}} to the |container|'s clip rect as described in <a>apply scroll margin to a scrollport</a>.
	4. If |container| has a <a>content clip</a> or a css <a>clip-path</a> property,
		update |intersectionRect| by applying |container|'s clip.
	5. If |container| is the root element of a <a>browsing context</a>,
		update |container| to be the <a>browsing context</a>'s {{document}};
		otherwise, update |container| to be the <a>containing block</a>
		of |container|.
4. Map |intersectionRect| to the coordinate space of |root|.
5. Update |intersectionRect| by intersecting it with the <a>root intersection rectangle</a>.
6. Map |intersectionRect| to the coordinate space of the <a>viewport</a> of the {{document}} containing |target|.
7. Return |intersectionRect|.

<h4 id='update-intersection-observations-algo'>
Run the Update Intersection Observations Steps</h4>

To <dfn export>run the update intersection observations steps</dfn> for a
<a>Document</a> |document| given a timestamp |time|, run these steps:

1. Let |observer list| be a list of all {{IntersectionObserver}}s
	whose {{IntersectionObserver/root}} is in the DOM tree of |document|.
	For the <a>top-level browsing context</a>, this includes <a>implicit root observers</a>.
2. For each |observer| in |observer list|:
	1. Let |rootBounds| be |observer|'s <a>root intersection rectangle</a>.
	2. For each |target| in |observer|'s internal {{[[ObservationTargets]]}} slot, processed in the same order that {{observe()}} was called on each |target|:
		1. Let:
			- |thresholdIndex| be 0.
			- |isIntersecting| be false.
			- |targetRect| be a {{DOMRectReadOnly}} with |x|, |y|, |width|, and |height| set to 0.
			- |intersectionRect| be a {{DOMRectReadOnly}} with |x|, |y|, |width|, and |height| set to 0.
		2. If the <a>intersection root</a> is not the <a>implicit root</a>,
			and |target| is not in the same {{document}} as the <a>intersection root</a>,
			skip to step 11.
		3. If the <a>intersection root</a> is an {{Element}},
			and |target| is not a descendant of the <a>intersection root</a>
			in the <a>containing block chain</a>, skip to step 11.
		4. Set |targetRect| to the {{DOMRectReadOnly}} obtained by <a>getting the bounding box</a> for
			|target|.
		4. Let |intersectionRect| be the result of running the <a>compute the intersection</a>
			algorithm on |target| and |observer|'s <a>intersection root</a>.
		5. Let |targetArea| be |targetRect|'s area.
		6. Let |intersectionArea| be |intersectionRect|'s area.
		7. Let |isIntersecting| be true if |targetRect| and |rootBounds| intersect or are edge-adjacent,
			even if the intersection has zero area (because |rootBounds| or |targetRect| have
			zero area).
		9. If |targetArea| is non-zero, let |intersectionRatio| be |intersectionArea| divided by |targetArea|.<br>
			Otherwise, let |intersectionRatio| be <code>1</code> if |isIntersecting| is true, or <code>0</code> if |isIntersecting| is false.
		10. Set |thresholdIndex| to the index of the first entry in |observer|.{{thresholds}} whose value is greater than |intersectionRatio|, or the length of |observer|.{{thresholds}} if |intersectionRatio| is greater than or equal to the last entry in |observer|.{{thresholds}}.
		11. Let |intersectionObserverRegistration| be the {{IntersectionObserverRegistration}} record
			in |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot
			whose {{IntersectionObserverRegistration/observer}} property is equal to |observer|.
		12. Let |previousThresholdIndex| be the |intersectionObserverRegistration|'s
		    {{IntersectionObserverRegistration/previousThresholdIndex}} property.
		13. Let |previousIsIntersecting| be the |intersectionObserverRegistration|'s
		    {{IntersectionObserverRegistration/previousIsIntersecting}} property.
		14. If |thresholdIndex| does not equal |previousThresholdIndex| or if
		    |isIntersecting| does not equal |previousIsIntersecting|,
			<a>queue an IntersectionObserverEntry</a>,
			passing in |observer|, |time|, |rootBounds|,
			|targetRect|, |intersectionRect|, |isIntersecting|, and |target|.
		15. Assign |thresholdIndex| to |intersectionObserverRegistration|'s
			{{IntersectionObserverRegistration/previousThresholdIndex}} property.
		16. Assign |isIntersecting| to |intersectionObserverRegistration|'s
			{{IntersectionObserverRegistration/previousIsIntersecting}} property.

<h3 id='lifetime'>
IntersectionObserver Lifetime</h2>

An {{IntersectionObserver}} will remain alive until both of these conditions hold:
<ul>
	<li>There are no scripting references to the observer.</li>
	<li>The observer is not observing any targets.
</ul>

An {{IntersectionObserver}} will continue observing a target until either the observer's {{IntersectionObserver/unobserve()}} method is called with the target as argument; or the observer's {{IntersectionObserver/disconnect()}} is called.

<h3 id='external-spec-integrations'>
External Spec Integrations</h3>

<h4 id='event-loop'>
HTML Processing Model: Event Loop</h4>

An Intersection Observer processing step exists as a substep
within the "<i>Update the rendering</i>" step,
in the <a>HTML Event Loops Processing Model</a>.

<h4 id='pending-initial-observation'>Pending initial IntersectionObserver targets</h4>
A {{document}} is said to have <dfn>pending initial IntersectionObserver targets</dfn>
if there is at least one {{IntersectionObserver}} meeting these criteria:
	<ol>
		<li>The |observer|'s {{IntersectionObserver|root}} is in the |document|
		   (for the <a>top-level browsing context</a>, this includes <a>implicit root observers</a>).
		</li>
		<li>The |observer| has at least one |target| in its {{[[ObservationTargets]]}} slot for which
		    no {{IntersectionObserverEntry}} has yet been queued.
		</li>
	</ol>

In the <a>HTML Event Loops Processing Model</a>, under the "<i>Update the rendering</i>" step, the "<i>Unnecessary rendering</i>" step should be modified to add an additional requirement for skipping the rendering update:

<ul><li>The |document| does not have <a>pending initial IntersectionObserver targets</a>.</li></ul>

<!-- ============================================================ -->
<h2 id=accessibility>Accessibility Considerations</h2>
<!-- ============================================================ -->

*This section is non-normative.*

There are no known accessibility considerations for the core IntersectionObserver specification (this document).
There are, however, related specifications and proposals that leverage and refer to this spec,
which might have their own accessibility considerations. In particular, specifications for
[[html#lazy-loading-attributes]] and [[css-contain-2#content-visibility]]
may have implications for [[html#find-in-page]], [[html#the-tabindex-attribute]], and
<a href="https://githumb.com/WICG/spatial-navigation">spatial navigation</a>.

<!-- ============================================================ -->
<h2 id=privacy>Privacy and Security</h2>
<!-- ============================================================ -->

*This section is non-normative.*

The main privacy concerns associated with this API relate to the information
it may provide to code running in the context of a cross-origin iframe
(i.e., the <a>cross-origin-domain target</a> case). In particular:

* There is no universal consensus on the privacy implications of
	revealing whether an iframe is within the global viewport.

* There is a risk that the API may be used to probe for information
	about the geometry of the global viewport itself,
	which may be used to deduce the user's hardware configuration.
	The motivation for disabling the effects of {{IntersectionObserver/rootMargin}}
	and {{IntersectionObserver/scrollMargin}}, and suppressing {{IntersectionObserverEntry/rootBounds}}
	for <a>cross-origin-domain targets</a> is to prevent such probing.

It should be noted that prior to {{IntersectionObserver}}, web developers
used other API's in very ingenious (and grotesque) ways to tease out the information
available from {{IntersectionObserver}}. As a purely practical matter, this API
does not reveal any information that was not already available by other means.

Another consideration is that {{IntersectionObserver}} uses {{DOMHighResTimeStamp}},
which has privacy and security considerations of its own. It is however unlikely that
{{IntersectionObserver}} is vulnerable to timing-related exploits. Timestamps are generated
at most once per rendering update (see [[#event-loop]]), which is far too
infrequent for the familiar kind of timing attack.

<!-- ============================================================ -->
<h2 id=internationalization>Internationalization</h2>
<!-- ============================================================ -->

*This section is non-normative.*

There are no known issues concerning internationalization.

<!-- ============================================================ -->
<h2 id=acknowledgements>Acknowledgements</h2>
<!-- ============================================================ -->

Special thanks to <a href="https://github.com/w3c/IntersectionObserver/graphs/contributors">all the contributors</a> for their technical input and suggestions that led to improvements to this
specification.
